//
//  WZUserInfoController.m
//  ETong
//
//  Created by wanzhao on 15/10/30.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZUserInfoController.h"
#import "CFolderMgr.h"

#import "WZMineInfoCell.h"
#import "KDActionSheet.h"
#import "FxImageCropViewController.h"
#import "MJExtension.h"
#import "MBProgressHUD+WZ.h"
#import "MJRefresh.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "UIBarButtonItem+category.h"
#import "MBProgressHUD+WZ.h"
#import "NetWorkShare.h"
#import "CContactModel.h"
#import "CContactMgr.h"


@interface WZUserInfoController ()<UITableViewDataSource, UITableViewDelegate, KDActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, FxImageCropViewControllerDelegate, WZMineInfoCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CContactModel *curAccount;

@property (nonatomic, strong)  NSData *imageData;

@property (nonatomic, copy) NSString *mobile;
@property (nonatomic, copy) NSString *telPhone;
@property (nonatomic, copy) NSString *mail;

StrongProperty CContactMgr *contactgr;

/**OA用户名*/
@property (nonatomic, copy) NSString *oaUserName;
/**OA 登陆密码*/
@property (nonatomic, copy) NSString *oaPwd;
/**OA userId*/
@property (nonatomic, copy) NSString *oaUserId;
/**OA 公司ID*/
@property (nonatomic, copy) NSString *oaCompanyID;
/**OA 姓名*/
@property (nonatomic, copy) NSString *oaName;
/**OA性别*/
@property (nonatomic, strong) NSString *oaSex;
/**OAmobile*/
@property (nonatomic, strong) NSString *oaMobile;
/**OA邮箱*/
@property (nonatomic, strong) NSString *oaMail;
@property (nonatomic, strong) NSString *oaTelephone;


@end

@implementation WZUserInfoController

- (void)dealloc
{
    NSLog(@"WZUserInfoController dealloc");
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    
    self.contactgr = [[CContactMgr alloc] init];
    self.curAccount = [self.contactgr loadContactWithUserCode:acc.userName];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    self.imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"personal_title"], 1.0);
    //为变量赋初始值
    self.mobile = nil;
    self.telPhone = nil;
    self.mail = nil;
    
    self.view.backgroundColor = WhiteColor;
    self.navigationItem.title = @"个人信息";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"compile_btn" selectedImageName:@"submit_btn" target:self sel:@selector(editUserInfo)];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, HARDWARE_SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = ClearColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    [self.view addSubview:self.tableView];
    
    __weak __typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadPersonalInfo];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
    
//    [self setupUI];

    [self loadPersonalInfo];
    
    // OA中的个人信息
//    [self getPersonInfor];
}


- (void)setupUI {
    
    // 获取OA账户信息
    self.oaUserName = [USER_DEFAULT objectForKey:@"oaUserName"];
    self.oaUserId = [USER_DEFAULT objectForKey:@"oaUserId"];
    self.oaPwd = [USER_DEFAULT objectForKey:@"oaPwd"];
    self.oaCompanyID = [USER_DEFAULT objectForKey:@"oaCompanyID"];
    self.oaName = [USER_DEFAULT objectForKey:@"oaName"];
    self.oaMail = [USER_DEFAULT objectForKey:@"oaMail"];
    self.oaSex = [USER_DEFAULT objectForKey:@"oaSex"];
    self.oaMobile = [USER_DEFAULT objectForKey:@"oaMobile"];
    self.oaTelephone = [USER_DEFAULT objectForKey:@"oaTelephone"];
    
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    
    self.contactgr = [[CContactMgr alloc] init];
    self.curAccount = [self.contactgr loadContactWithUserCode:acc.userName];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    self.imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"personal_title"], 1.0);
    
    //为变量赋初始值
    self.mobile = nil;
    self.telPhone = nil;
    self.mail = nil;
    
    
    // OA初始化个人信息
    self.mobile = self.oaMobile;
    self.telPhone = self.oaTelephone;
    self.mail = self.oaMail;
    
    
    
    self.view.backgroundColor = WhiteColor;
    self.navigationItem.title = @"个人信息";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"compile_btn" selectedImageName:@"submit_btn" target:self sel:@selector(editUserInfo)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, HARDWARE_SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = ClearColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    [self.view addSubview:self.tableView];
    
    __weak __typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadPersonalInfo];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
 
}

//从相册选择图片时，系统会默认将statubar设置成黑色，拍照选择照片时，系统会默认将statusbar隐藏，在以下两个方法中分别作处理可以解决问题
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!IsIOS7) {
        self.navigationController.navigationBar.tintColor = RGBCOLORWITH16COLOR(0x354d6c);
    } else {
        self.navigationController.navigationBar.barTintColor = RGBCOLORWITH16COLOR(0x354d6c);
    }

    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
    
    
    if ([navigationController isKindOfClass:[UIImagePickerController class]] &&
        ((UIImagePickerController *)navigationController).sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
        if (!IsIOS7) {
            navigationController.navigationBar.tintColor = RGBCOLORWITH16COLOR(0x354d6c);
        } else {
            navigationController.navigationBar.barTintColor = RGBCOLORWITH16COLOR(0x354d6c);
        }

    }
}


- (void)hideKeyboard:(NSNotification *)notice
{
    NSDictionary *keyboardInfo = notice.userInfo;
    
    UIViewAnimationCurve animationCurve;
    CGFloat animateDuration = [[keyboardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [[keyboardInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animateDuration];
    [UIView setAnimationCurve:animationCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    self.tableView.y = 0;
    
    [UIView commitAnimations];

}
- (void)showKeyboard:(NSNotification *)notice
{
    
    NSDictionary *keyboardInfo = notice.userInfo;
    UIViewAnimationCurve animationCurve;
    CGFloat animateDuration = [[keyboardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [[keyboardInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    NSValue *aValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [aValue CGRectValue];
    
   
   
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animateDuration];
    [UIView setAnimationCurve:animationCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    if (CGRectGetMaxY(cell.frame) + 64 > keyboardFrame.origin.y) {
        self.tableView.y = keyboardFrame.origin.y -  CGRectGetMaxY(cell.frame) - 64;
    } else {
        
    }
    [UIView commitAnimations];
}

- (void)hideKeyboard
{
    [self.view endEditing:YES];
    
}


#pragma mark 加载个人信息
- (void)loadPersonalInfo
{
    [NetWorkShare  getPersonalInfoWithUserId:self.oaUserId successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
    
        [self.tableView.header endRefreshing];
//        NSLog(@"%@",responseObject);
        if (responseObject != nil) {
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                CContactModel *acc = [CContactModel objectWithKeyValues:responseObject[@"userInfo"]];
                self.curAccount.Telephone = acc.Telephone;
                self.curAccount.MobileTelephone = acc.MobileTelephone;
                self.curAccount.Email = acc.Email;
                self.curAccount.DEPNAME = acc.DEPNAME;
                self.curAccount.Position = acc.Position;
                self.curAccount.SEX = acc.SEX;
                
                self.curAccount.UserName = acc.UserName;
                
                [self.contactgr updateContact:self.curAccount];
                [self.tableView reloadData];
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }

        } else {
            [MBProgressHUD showError:@"未知错误"];
        }
        
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self.tableView.header endRefreshing];
            [MBProgressHUD showError:@"网络异常"];
    }];

}

// OA个人信息
- (void)getPersonInfor {
    
    [NetWorkShare getPersonalInfoWithUserId:self.oaUserId successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([[responseObject objectForKey:responseObject[@"success"]] boolValue]) {
            
           // TODO: 成功后回调
            
        } else {
            
            [MBProgressHUD showError:responseObject[@"success"]];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:NETWORKNERROR];
    }];
}

#pragma mark 更新头像
- (void)updateHeaderImage
{
    [self.view endEditing:YES];
    KDActionSheet *sheet = [[KDActionSheet alloc] initWithTitle:nil message:nil cancelButtonTitle:@"取消" buttonTitles:@[@"拍照",@"从手机相册中选取"] delegate:self];
    [sheet.bigImageView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageWithData:self.imageData]];
    [sheet showInView:self.view];
}

- (void)kdActionSheet:(KDActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            [imagePickerController setDelegate:self];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
            }
            else
            {
                [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            }
            //        [imagePickerController setAllowsEditing:YES];
            [self presentViewController:imagePickerController animated:YES completion:nil];

        }
            break;
            
        case 1:
        {
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            [imagePickerController setDelegate:self];
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [self presentViewController:imagePickerController animated:YES completion:NULL];

        }
            break;
            
        case 2:
        {
        
        }
            break;
        default:
            break;
    }
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //    bug
    UIImage *photo = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    FxImageCropViewController *imageCropVC = [[FxImageCropViewController alloc] initWithImage:photo cropMode:RSKImageCropModeCustom cropSize:CGSizeMake(OppositeWidthRate(200), OppositeWidthRate(200))];
    
    imageCropVC.delegate = self;
    [picker pushViewController:imageCropVC animated:YES];
    
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^(){
    }];
}



- (void)imageCropViewControllerDidCancelCrop:(FxImageCropViewController *)controller
{
    self.imageData = nil;
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)imageCropViewController:(FxImageCropViewController *)controller didCropImage:(UIImage *)croppedImage
{
    UIImage *image = croppedImage;
//    image = [self scaleToSize:image size:CGSizeMake(320, 320)];
    self.imageData = UIImageJPEGRepresentation(image, 1.0);
    [self dismissViewControllerAnimated:YES completion:^{
        [self.tableView reloadData];
    }];
    
    
    
}


- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}


#pragma mark tableView相关
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = ClearColor;
    
    
    UIView *backImageView = [[UIView alloc] init];
    backImageView.frame = CGRectMake(OppositeWidthRate(16), OppositeHeightRate(24), OppositeWidthRate(90), OppositeHeightRate(90));
    backImageView.backgroundColor = ClearColor;
    backImageView.layer.cornerRadius = backImageView.width / 2.0f;
    backImageView.layer.borderColor = RGBCOLORWITH16COLOR(0xcccccc).CGColor;
    backImageView.layer.borderWidth = 1.0f;
    backImageView.layer.masksToBounds = YES;
    [header addSubview:backImageView];
    
    
    UIButton *imageView = [UIButton buttonWithType:UIButtonTypeCustom];
    imageView.frame = CGRectMake(0, 0, OppositeWidthRate(80), OppositeHeightRate(80));
    imageView.center = backImageView.center;
    imageView.backgroundColor = ClearColor;
    imageView.layer.cornerRadius = imageView.width / 2.0f;
    imageView.layer.masksToBounds = YES;
    
    if (self.navigationItem.rightBarButtonItem.selected) {
        imageView.userInteractionEnabled = YES;
    } else {
        imageView.userInteractionEnabled = NO;
    }
    
    imageView.adjustsImageWhenHighlighted = NO;
    [imageView addTarget:self action:@selector(updateHeaderImage) forControlEvents:UIControlEventTouchUpInside];
    
    
    [imageView sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageWithData:self.imageData]];
    [header addSubview:imageView];
    
    
    UIButton *sexBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if ([self.curAccount.SEX isEqualToString:@"1"]) {
        [sexBtn setImage:[UIImage imageNamed:@"man"] forState:UIControlStateNormal];
    } else {
        [sexBtn setImage:[UIImage imageNamed:@"woman"] forState:UIControlStateNormal];
    }
    sexBtn.userInteractionEnabled = NO;
    [header addSubview:sexBtn];

   
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.font = Font18;
    nameLabel.textColor = RGBCOLORWITH16COLOR(0x333333);
    nameLabel.text = self.curAccount.UserName;
    nameLabel.backgroundColor = ClearColor;
    
    CGSize nameSize = [self.curAccount.UserName sizeWithFont:nameLabel.font maxSize:CGSizeMake( HARDWARE_SCREEN_WIDTH - CGRectGetMaxX(backImageView.frame) - OppositeWidthRate(24) - sexBtn.currentImage.size.width,MAXFLOAT)];
    nameLabel.frame = CGRectMake(OppositeWidthRate(24) + CGRectGetMaxX(backImageView.frame), OppositeHeightRate(45), nameSize.width, OppositeHeightRate(20));
    [header addSubview:nameLabel];
    
    //设置性别控件的frame
     sexBtn.frame = CGRectMake(CGRectGetMaxX(nameLabel.frame) + OppositeWidthRate(12), OppositeHeightRate(45), sexBtn.currentImage.size.width, OppositeHeightRate(20));
    
    UILabel *joblabel = [[UILabel alloc] init];
    joblabel.font = Font15;
    joblabel.textColor = RGBCOLORWITH16COLOR(0x666666);
    joblabel.text = [NSString stringWithFormat:@"%@  %@",self.curAccount.DEPNAME,self.curAccount.Position];
    joblabel.backgroundColor = ClearColor;
    joblabel.frame = CGRectMake(OppositeWidthRate(24) + CGRectGetMaxX(backImageView.frame), CGRectGetMaxY(nameLabel.frame) + OppositeHeightRate(16), HARDWARE_SCREEN_WIDTH - CGRectGetMaxX(backImageView.frame) - OppositeWidthRate(48), OppositeHeightRate(20));
    
    
    [header addSubview:joblabel];
    
    
    return header;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WZMineInfoCell *cell = [WZMineInfoCell mineInfoCellWithTableView:tableView];
    switch (indexPath.row) {
        case 0:
        {
            [cell.iconButton setImage:[UIImage imageNamed:@"personal_phone"] forState:UIControlStateNormal];
            cell.titField.text = self.curAccount.MobileTelephone;
            cell.textViewTag = TextViewMobileTag;
        }
            break;
        case 1:
        {
            [cell.iconButton setImage:[UIImage imageNamed:@"personal_tel"] forState:UIControlStateNormal];
            cell.titField.text = self.curAccount.Telephone;
            cell.textViewTag = TextViewTelPhoneTag;

        }
            break;
        case 2:
        {
            [cell.iconButton setImage:[UIImage imageNamed:@"personal_email"] forState:UIControlStateNormal];
            cell.titField.text = self.curAccount.Email;
            cell.textViewTag = TextViewMailTag;

        }
            break;
        default:
            break;
    }
    cell.InfoCellDelegate = self;
    cell.isEdit = self.navigationItem.rightBarButtonItem.selected;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"DFAFAFA");
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return OppositeHeightRate(60);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return OppositeHeightRate(130);
}

-(BOOL)isValidateEmail:(NSString *)email {
    
    if (M_ISSTRNULL(email)) {
        return NO;
    }
    if (email.length > 50) {
        return NO;
    }
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
-(BOOL) isValidateMobile:(NSString *)mobile
{
    if (M_ISSTRNULL(mobile)) {
        return NO;
    }
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

- (BOOL)isValidateTel:(NSString *)tel
{
    if (M_ISSTRNULL(tel)) {
        return NO;
    }
    if (tel.length > 20) {
        return NO;
    }
    NSString *telRegex = @"(([0-9]{3,4})|([0-9]{3,4}-))?\\d{7,8}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    return [emailTest evaluateWithObject:tel];

}

#pragma mark 编辑用户信息
- (void)editUserInfo
{
    if (self.navigationItem.rightBarButtonItem.selected) {
        
        [self.view endEditing:YES];
        if (self.mail == nil) {
            self.mail = self.curAccount.Email;
        }
        if (self.mobile == nil) {
            self.mobile = self.curAccount.MobileTelephone;
        }
        if (self.telPhone == nil) {
            self.telPhone = self.curAccount.Telephone;
        }
        
        if (![self isValidateMobile:self.mobile]) {
            [MBProgressHUD showError:@"您输入的手机号不合法"];
            return;
        }
        
        if (![self isValidateTel:self.telPhone]) {
            [MBProgressHUD showError:@"您输入的座机号不合法"];
            return;
        }
        if (![self isValidateEmail:self.mail]) {
            [MBProgressHUD showError:@"你输入的邮箱不合法"];
            return;
        }
        
        
        
        //生成更改后的用户信息的字典
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"userid"] = self.curAccount.UserID;
        dict[@"mobile"] = self.mobile;
        dict[@"telephone"] = self.telPhone;
        dict[@"mail"] = self.mail;
        
        
        //更新用户信息
        [MBProgressHUD showMessage:nil toView:self.view];
        [NetWorkShare updatePersonalInfoWithUpdateDict:dict successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            if (responseObject != nil) {
                if ([[responseObject objectForKey:@"success"] boolValue]) {
                    //信息更新成功后更新数据库中存储的用户信息
                    self.curAccount.MobileTelephone = self.mobile;
                    self.curAccount.Telephone = self.telPhone;
                    self.curAccount.Email = self.mail;
                    [self.contactgr updateContact:self.curAccount];
                    
                } else {
                    [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
                }

            } else {
                [MBProgressHUD showError:@"未知错误"];
            }
            
        //切换按钮的状态
        self.navigationItem.rightBarButtonItem.selected = !self.navigationItem.rightBarButtonItem.selected;
        [self.tableView reloadData];
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:@"网络异常"];
             //切换按钮的状态
            self.navigationItem.rightBarButtonItem.selected = !self.navigationItem.rightBarButtonItem.selected;
            [self.tableView reloadData];
        }];
    } else {
        
        //切换按钮的状态
        self.navigationItem.rightBarButtonItem.selected = !self.navigationItem.rightBarButtonItem.selected;
        [self.tableView reloadData];

    }

}


#pragma mark infoCellDelegate
- (void)textViewDidChangeWithText:(NSString *)infoText textViewTag:(TextViewTag)textViewTag
{
    switch (textViewTag) {
        case TextViewMobileTag:
        {
            self.mobile = infoText;
        }
            break;
        case TextViewTelPhoneTag:
        {
            self.telPhone = infoText;
        }
            break;
        case TextViewMailTag:
        {
            self.mail = infoText;
        }
            break;
   
        default:
            break;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
@end
